package com.rocketmq.mq.producer;

import jakarta.annotation.PostConstruct;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;



/****************************************
 * 作者：HuMaSiYuan
 * 邮箱：siyueguoji@163.com
 * 日期：2023/10/11 8:37
 * 功能描述：
 ****************************************/
@Component
public class Producer {


    @Value("${rocketmq.producer.producerGroup}")
    private String producerGroup;

    // 生产者
    private DefaultMQProducer producer;

    @Value("${rocketmq.namesrvAddr}")
    private String namesrvAddr;


    @PostConstruct
    public void defaultMQProducer() {

        // 生产者的组名
        producer = new DefaultMQProducer(producerGroup);
        producer.setNamesrvAddr(namesrvAddr);
        producer.setVipChannelEnabled(false);

        try {
            producer.start();
            System.out.println("-------->:producer启动了");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String send(String topic, String tags, String body) throws UnsupportedEncodingException, MQBrokerException, RemotingException, InterruptedException, MQClientException {
        Message message = new Message(topic, tags, body.getBytes(RemotingHelper.DEFAULT_CHARSET));
        StopWatch stop = new StopWatch();
        stop.start();
        SendResult result = producer.send(message);
        System.out.println("发送响应：MsgId:" + result.getMsgId() + "，发送状态:" + result.getSendStatus());
        stop.stop();
        return "{\"MsgId\":\""+result.getMsgId()+"\"}";
    }


}
